import { createRouter, createWebHistory } from 'vue-router'
import { useMenuStore } from "@/stores/menu.js"
import { useUserStore } from "@/stores/user.js"

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人中心' }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: { title: '账户设置' }
      }
    ]
  },
]

const router = createRouter({
  history: createWebHistory('/admin/'),
  routes
})

// 路由守卫
router.beforeEach(function(to, from) {
  const menuStore = useMenuStore()
  const userStore = useUserStore()

  if (to.meta.title) {
    document.title = `${to.meta.title}-MonoAdmin`
  }

  // 如果访问登录页
  if (to.path === '/login') {
    // 如果已经登录，重定向到首页
    if (userStore.token) {
      return '/'
    }
    return true
  } else {
    // 检查是否有token
    if (!userStore.token) {
      return '/login'
    }

    // 如果有token但菜单为空，尝试获取菜单
    if (menuStore.menuList.length === 0) {
      return menuStore.getMenus()
        .then(function(accessRoutes) {
          if (accessRoutes && accessRoutes.length > 0) {
            for (let index = 0; index < accessRoutes.length; index++) {
              const item = accessRoutes[index];

              if (!router.hasRoute(item.name)) {
                router.addRoute('Layout', item)
              }
            }
            return { ...to, replace: true }
          } else {
            // 如果获取菜单失败或为空，跳转到登录页
            return '/login'
          }
        })
        .catch(function(error) {
          console.error('获取菜单失败:', error)
          // 获取菜单失败，清除token并跳转到登录页
          userStore.token = null
          userStore.userInfo = null
          return '/login'
        })
    }

    return true
  }
})

export default router